const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const webpack = require("webpack");
const { config } = require("process");

module.exports = {
  mode: "development",
  entry: path.resolve(__dirname, "src/login/index.js"),
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "./login/first_bundle.js",
    clean: true,
  },
  plugins: [
    // 生成html
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "public/login.html"),
      filename: path.resolve(__dirname, "dist/login/login.html"),
      useCdn: process.env.NODE_ENV === "production",
    }),
    // 提取css
    new MiniCssExtractPlugin({
      filename: "./login/first_bundle.css",
    }),
    // 注入环境变量
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
    }),
  ],
  module: {
    rules: [
      // 打包css
      {
        test: /\.css$/i,
        // use: ["style-loader", "css-loader"],
        use: [
          process.env.NODE_ENV === "production"
            ? MiniCssExtractPlugin.loader
            : "style-loader",
          "css-loader",
        ],
      },
      // 打包less
      {
        test: /\.less$/i,
        use: [
          // compiles Less to CSS
          process.env.NODE_ENV === "production"
            ? MiniCssExtractPlugin.loader
            : "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
      // 打包图片
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: "asset",
        generator: {
          filename: "assets/[hash][ext][query]",
        },
      },
    ],
  },
  optimization: {
    minimizer: [
      // 在 webpack@5 中，你可以使用 `...` 语法来扩展现有的 minimizer（即 `terser-webpack-plugin`），将下一行取消注释保证js代码正常压缩
      `...`,
      new CssMinimizerPlugin(),
    ],
  },
  // 解析
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
};
if( process.env.NODE_ENV === "production") {
  // 使用了CDN加速，防止打包第三方库
  config.externals = {
    "bootstrap/dist/css/bootstrap.min.css": "bootstrapCss",
    "bootstrap/dist/js/bootstrap.bundle.min.js": "bootstrapJs",
  };
}
